package com.example.performance.web.controller;

import com.example.performance.model.LoadTestConfig;
import com.example.performance.service.ScenarioManagementService;
import com.example.performance.service.TestExecutionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * REST API控制器
 * 提供场景配置和测试执行的REST接口
 */
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class ApiController {

    private static final Logger logger = LoggerFactory.getLogger(ApiController.class);

    @Autowired
    private ScenarioManagementService scenarioService;

    @Autowired
    private TestExecutionService testExecutionService;

    /**
     * 获取所有配置摘要
     */
    @GetMapping("/configs")
    public ResponseEntity<List<ScenarioManagementService.ConfigSummary>> getAllConfigs() {
        try {
            List<ScenarioManagementService.ConfigSummary> configs = scenarioService.getAllConfigSummaries();
            return ResponseEntity.ok(configs);
        } catch (Exception e) {
            logger.error("获取配置列表失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 根据ID获取配置详情
     */
    @GetMapping("/configs/{configId}")
    public ResponseEntity<LoadTestConfig> getConfigById(@PathVariable String configId) {
        try {
            LoadTestConfig config = scenarioService.getConfigById(configId);
            return ResponseEntity.ok(config);
        } catch (Exception e) {
            logger.error("获取配置失败: {}", configId, e);
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 创建新配置
     */
    @PostMapping("/configs")
    public ResponseEntity<Map<String, Object>> createConfig(@RequestBody LoadTestConfig config) {
        try {
            // 验证配置
            ScenarioManagementService.ValidationResult validation = scenarioService.validateConfig(config);
            if (!validation.isValid()) {
                Map<String, Object> response = new HashMap<String, Object>();
                response.put("success", false);
                response.put("errors", validation.getErrors());
                return ResponseEntity.badRequest().body(response);
            }

            String configId = scenarioService.saveConfig(config, null);

            Map<String, Object> response = new HashMap<String, Object>();
            response.put("success", true);
            response.put("configId", configId);
            response.put("message", "配置创建成功");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("创建配置失败", e);
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("success", false);
            response.put("message", "配置创建失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 更新配置
     */
    @PutMapping("/configs/{configId}")
    public ResponseEntity<Map<String, Object>> updateConfig(@PathVariable String configId,
            @RequestBody LoadTestConfig config) {
        try {
            // 验证配置
            ScenarioManagementService.ValidationResult validation = scenarioService.validateConfig(config);
            if (!validation.isValid()) {
                Map<String, Object> response = new HashMap<String, Object>();
                response.put("success", false);
                response.put("errors", validation.getErrors());
                return ResponseEntity.badRequest().body(response);
            }

            scenarioService.saveConfig(config, configId);

            Map<String, Object> response = new HashMap<String, Object>();
            response.put("success", true);
            response.put("message", "配置更新成功");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("更新配置失败: {}", configId, e);
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("success", false);
            response.put("message", "配置更新失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 删除配置
     */
    @DeleteMapping("/configs/{configId}")
    public ResponseEntity<Map<String, Object>> deleteConfig(@PathVariable String configId) {
        try {
            boolean deleted = scenarioService.deleteConfig(configId);

            Map<String, Object> response = new HashMap<String, Object>();
            if (deleted) {
                response.put("success", true);
                response.put("message", "配置删除成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "配置不存在或删除失败");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.error("删除配置失败: {}", configId, e);
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("success", false);
            response.put("message", "配置删除失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 验证配置
     */
    @PostMapping("/configs/validate")
    public ResponseEntity<ScenarioManagementService.ValidationResult> validateConfig(
            @RequestBody LoadTestConfig config) {
        try {
            ScenarioManagementService.ValidationResult result = scenarioService.validateConfig(config);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("验证配置失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 创建新的空配置模板
     */
    @PostMapping("/configs/template")
    public ResponseEntity<LoadTestConfig> createConfigTemplate() {
        try {
            LoadTestConfig template = scenarioService.createNewConfig();
            return ResponseEntity.ok(template);
        } catch (Exception e) {
            logger.error("创建配置模板失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 启动测试
     */
    @PostMapping("/tests/start")
    public ResponseEntity<Map<String, Object>> startTest(@RequestBody StartTestRequest request) {
        try {
            LoadTestConfig config = scenarioService.getConfigById(request.getConfigId());
            String sessionId = UUID.randomUUID().toString().replace("-", "");

            TestExecutionService.TestSession session = testExecutionService.startTest(sessionId, config);

            Map<String, Object> response = new HashMap<String, Object>();
            response.put("success", true);
            response.put("sessionId", sessionId);
            response.put("message", "测试启动成功");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("启动测试失败", e);
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("success", false);
            response.put("message", "测试启动失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 停止测试
     */
    @PostMapping("/tests/{sessionId}/stop")
    public ResponseEntity<Map<String, Object>> stopTest(@PathVariable String sessionId) {
        try {
            boolean stopped = testExecutionService.stopTest(sessionId);

            Map<String, Object> response = new HashMap<String, Object>();
            if (stopped) {
                response.put("success", true);
                response.put("message", "测试停止成功");
            } else {
                response.put("success", false);
                response.put("message", "测试会话不存在");
            }

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("停止测试失败: {}", sessionId, e);
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("success", false);
            response.put("message", "测试停止失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 获取测试会话状态
     */
    @GetMapping("/tests/{sessionId}")
    public ResponseEntity<TestExecutionService.TestSession> getTestSession(@PathVariable String sessionId) {
        try {
            TestExecutionService.TestSession session = testExecutionService.getTestSession(sessionId);
            if (session != null) {
                return ResponseEntity.ok(session);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.error("获取测试会话失败: {}", sessionId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 获取所有活跃的测试会话
     */
    @GetMapping("/tests")
    public ResponseEntity<Map<String, TestExecutionService.TestSession>> getAllTestSessions() {
        try {
            Map<String, TestExecutionService.TestSession> sessions = testExecutionService.getAllActiveSessions();
            return ResponseEntity.ok(sessions);
        } catch (Exception e) {
            logger.error("获取测试会话列表失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 启动测试请求对象
     */
    public static class StartTestRequest {
        private String configId;

        public String getConfigId() {
            return configId;
        }

        public void setConfigId(String configId) {
            this.configId = configId;
        }
    }
}